package com.taobao.mycamunda.service;

import com.taobao.mycamunda.controller.WorkflowController;
import com.taobao.mycamunda.model.ActivityNodeVO;
import com.taobao.mycamunda.util.ActivityNodeUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.xml.instance.DomElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Created by zhangfei
 **/
@Service
public class WorkflowTaskService {
    @Autowired
    private HistoryService historyService;

    @Autowired
    private RepositoryService repositoryService;

    public WorkflowTaskService(){

    }

    public List<ActivityNodeVO> getActivityNodeList(String procId) {
        List<ActivityNodeVO> activityNodeVOList = new ArrayList<>();
        if(StringUtils.isBlank(procId)){
            return activityNodeVOList;
        }

        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(procId).singleResult();
        if(ObjectUtils.isEmpty(historicProcessInstance)){
            return activityNodeVOList;
        }

        BpmnModelInstance bpmnModelInstance = repositoryService.getBpmnModelInstance(historicProcessInstance.getProcessDefinitionId());
        if(ObjectUtils.isEmpty(bpmnModelInstance)){
            return activityNodeVOList;
        }

        List<DomElement> domElementList = bpmnModelInstance.getDocument().getRootElement().getChildElements();
        if(ObjectUtils.isEmpty(domElementList)){
            return activityNodeVOList;
        }

        DomElement domElement = domElementList.stream().filter(it -> "process".equals(it.getLocalName())).findFirst().orElse(null);
        if(ObjectUtils.isEmpty(domElement)){
            return activityNodeVOList;
        }

        activityNodeVOList.addAll(ActivityNodeUtils.createActivityNodeBySubProcessElement(domElement));
        return activityNodeVOList;
    }
}
